package ldh.im.fxgui.controller.handler;

import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.VBox;
import ldh.im.fxbase.util.ThreadPoolUtil;
import ldh.im.fxbase.pojo.DbMessage;

import java.util.List;

public class SendMessageVBoxHandler implements SendMessageHandler {

    private ObservableList<DbMessage> items = FXCollections.observableArrayList();
    private VBox messageList;
    private ScrollPane scrollPane;
    private int maxSize = 200;

    public SendMessageVBoxHandler() {

    }

    public SendMessageVBoxHandler(int maxSize) {
        this.maxSize = maxSize;
    }

    public Node createMessagePaneNode() {
        messageList = new VBox();
        scrollPane = new ScrollPane(messageList);
        return scrollPane;
    }

    @Override
    public void addMessage(DbMessage message) {
        if (items.size() > maxSize) {
            int removeSize = items.size() - maxSize;
            items.remove(0, removeSize);
            messageList.getChildren().remove(0, removeSize);
        }
        items.add(message);
        messageList.getChildren().add(createMessagePane(message));
        scrollPane.setVvalue(1.0);
        ThreadPoolUtil.schedule(()-> {
            Platform.runLater(()-> scrollPane.setVvalue(1.0));
        }, 10);
    }

    @Override
    public void addMessages(List<DbMessage> messages) {
        items.addAll(messages);
        for(DbMessage message : messages) {
            messageList.getChildren().add(createMessagePane(message));
        }
        scrollPane.setVvalue(1.0);
        ThreadPoolUtil.schedule(()-> {
            Platform.runLater(()-> scrollPane.setVvalue(1.0));
        }, 10);
    }

    @Override
    public ObservableList<DbMessage> getItems() {
        return items;
    }
}
